<template>
	<view class="countdown-container">
		<view class="time-box" v-if="day">{{ day + '天'}}</view>
		<text class="colon" v-if="day"></text>
		<view class="time-box">{{ hours }}</view>
		<text class="colon">:</text>
		<view class="time-box">{{ minutes }}</view>
		<text class="colon">:</text>
		<view class="time-box">{{ seconds }}</view>
	</view>
</template>

<script>
	export default {
		props: {
			endTimestamp: { // 后端传入的结束时间戳（秒/毫秒级）
				type: Number,
				required: true
			},
			isMillisecond: { // 时间戳是否为毫秒级（默认秒级）
				type: Boolean,
				default: false
			},
			day: { // 时间戳是否为毫秒级（默认秒级）
				type: String,
				default: false
			}
		},
		data() {
			return {
				remainingTime: 0,
				timer: null
			}
		},
		computed: {
			hours() {
				return Math.floor((this.remainingTime % 86400) / 3600).toString().padStart(2, '0')
			},
			minutes() {
				return Math.floor((this.remainingTime % 3600) / 60).toString().padStart(2, '0')
			},
			seconds() {
				return (this.remainingTime % 60).toString().padStart(2, '0')
			}
		},
		mounted() {
			this.startCountdown()
		},
		beforeDestroy() {
			clearInterval(this.timer)
		},
		methods: {
			startCountdown() {
				this.timer = setInterval(() => {
					const now = Math.floor(Date.now() / 1000)
					const endTime = this.isMillisecond ?
						Math.floor(this.endTimestamp / 1000) :
						this.endTimestamp

					this.remainingTime = Math.max(0, endTime - now)

					if (this.remainingTime <= 0) {
						clearInterval(this.timer)
						this.$emit('countdown-end')
					}
				}, 1000)
			}
		}
	}
</script>

<style>
	.countdown-container {
		display: flex;
		align-items: center;
	}

	.time-box {
		/* width: 46rpx; */
		height: 46rpx;
		padding: 0 8rpx;
		background: #000000;
		border-radius: 8rpx;
		font-size: 28rpx;
		font-family: DIN, DIN-Bold;
		font-weight: 700;
		color: #ffffff;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.colon {
		margin: 0 5rpx;
		font-size: 28rpx;
		font-family: DIN, DIN-Bold;
		font-weight: 700;
		text-align: left;
		color: #ffffff;
	}
</style>